/*
Name: Ajinkya Arun Gurav 
Div : H  Roll No:21
GR No : 121237
Subject : Network Security Lab

Lab 5: Implement encryption and decrypzztion using RC4 Algorithm.
 */
import java.io.*;
class rc4
{
	public static void main(String args[])
	{
		int i=0,j=0,temp=0;
		String ptxt=null,key=null;
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		try{
		System.out.println("Enter plaintext");
		ptxt=br.readLine();
		System.out.println("Enter keytext\t\t");
		key=br.readLine();
		}
		catch(Exception e)
		{
			System.out.println("Exception is: "+e.getLocalizedMessage());
		}
		int s[]=new int[256];
		int k[]=new int[256];
		int cipher[]=new int[ptxt.length()];
		int decrypt[]=new int[ptxt.length()];
		char ptxtc[]=ptxt.toCharArray();
		char keyc[]=key.toCharArray();
		int ptxti[]=new int[ptxt.length()];
		int keyi[]=new int[key.length()];
		
		for(i=0;i<ptxt.length();i++)
		{
			ptxti[i]=ptxtc[i];
		}
		for(i=0;i<key.length();i++)
		{
			keyi[i]=keyc[i];
		}
		for(i=0;i<256;i++)
		{
			s[i]=i;
			k[i]=keyi[i%key.length()];
		}
		j=0;
		for(i=0;i<255;i++)
		{
			j=(j+s[i]+k[i])%256;
			temp=s[i];
			s[i]=s[j];
			s[j]=temp;
		}
		i=0;
		j=0;
		int z=0;
		for(int l=0;l<ptxt.length();l++)
		{
			i=(l+1)%256;
			j=(j+s[i])%256;
			temp=s[i];
			s[i]=s[j];
			s[j]=temp;
			z=s[(s[i]+s[j])%256];
			cipher[l]=z^ptxti[l];
			decrypt[l]=z^cipher[l];
		}
		System.out.println("ENCRYPTED:");
		disp(cipher);
		System.out.println("DECRYPTED:");
		disp(decrypt);
		
	}

	private static void disp(int[] txtcipher) {
		char StrToChar[]=new char[txtcipher.length];
		for(int increment=0;increment<txtcipher.length;increment++)
		{
			StrToChar[increment]=(char)txtcipher[increment];
		System.out.print(StrToChar[increment]);
		}
		System.out.println("\n");
	}
}
/*
Enter plaintext
ajinkya
Enter keytext		
abc
ENCRYPTED:
���G3�?

DECRYPTED:
ajinkya
*/